using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using Microsoft.EntityFrameworkCore;
using CMS_Admin.Backend.Api.Repository;
using CMS_Admin.Backend.Api.Filters;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using CMS_Admin.Backend.Api.ParamModel;
using System.Text;
using System.Reflection;
using System.IO;
using Microsoft.Extensions.FileProviders;

namespace CMS_Admin.Backend.Api
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        private string allowCors = "AllowCors";

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddCors(Options =>
            {
                Options.AddPolicy(allowCors, builder =>
                 {
                     builder.AllowAnyHeader()
                     .AllowAnyMethod()
                     .AllowAnyOrigin();
                 });
            });


            // 注册数据库上下文到容器
            services.AddDbContext<CMS_Admin.Backend.Api.Db.AdminDb>(o => o.UseSqlServer());
            // 注册对数据库的基本操作服务到容器
            services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));

            // 注册验证器（使用何种配置来验证token）
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(option =>
            {
                // 是否要求使用https
                option.RequireHttpsMetadata = false;
                // 是否保存token
                option.SaveToken = true;
                // 使用配置中间件，获得token的配置
                var tokenParameter = Configuration.GetSection("TokenParameter").Get<TokenParameter>();
                // 验证器的核心属性
                option.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,//要不要验证生成token的密钥
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenParameter.Secret)),
                    ValidateIssuer = true, // 要不要验证发行token的人（个人或者组织）
                    ValidIssuer = tokenParameter.Issuer,
                    ValidateAudience = false // 是否验证受众
                };
            });


            services.AddControllers(options =>
            {
                options.Filters.Add(typeof(AuditLogActionFilter));
            });

            #region Swagger Api接口文档
            services.AddSwaggerGen(c =>
           {
               c.SwaggerDoc("v1", new OpenApiInfo
               {
                   Version = "v1.0.0",//版本号
                   Title = "阎罗殿生死簿API",//标题
                   Description = "关于阎罗殿生死簿的相关api",//描述
                   TermsOfService = new Uri("https://xiatianyu.cn"),//服务条款
                   Contact = new OpenApiContact
                   {
                       Name = "小鬼",//联系人
                       Email = "mxie7122@gmail.com",//邮箱地址
                       Url = new Uri("https://cxff.xiatianyu.cn"),//网址
                   },
                   License = new OpenApiLicense
                   {
                       Name = "MIT",//协议
                       Url = new Uri("https://xiatianyu.cn")//协议网址
                   }
               });
               // 获取xml文件名
               var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
               // 获取xml文件路径
               var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
               // 添加控制器层注释，true表示显示控制器注释
               c.IncludeXmlComments(xmlPath, true);

               //添加Authorization
               c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
               {
                   Description = "JWT Authorization header using the Bearer scheme.",
                   Name = "Authorization",
                   In = ParameterLocation.Header,
                   Scheme = "bearer",
                   Type = SecuritySchemeType.Http,
                   BearerFormat = "JWT"
               });

               c.AddSecurityRequirement(new OpenApiSecurityRequirement
               {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }
                        },
                        new List<string>()
                    }
               });

           });

            #endregion
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "CMS_Admin.Backend.Api v1"));

            }



            // app.UseHttpsRedirection();




            app.UseRouting();

            // 跨域
            app.UseCors(allowCors);

            #region 静态资源中间件 http://localhost:5000/uploadfiles/……
            string filepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "uploadfiles");
            if (!Directory.Exists(filepath))
                Directory.CreateDirectory(filepath);
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(filepath),
                RequestPath = "/uploadfiles"
            });
            #endregion


            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
